package com.ms.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.Query;
import com.ms.common.utils.R;
import com.ms.content.dao.BargainActivityDao;
import com.ms.content.dao.BargainingItemDao;
import com.ms.content.entity.BargainActivityEntity;
import com.ms.content.entity.BargainingItemEntity;
import com.ms.content.entity.GoodsEntity;
import com.ms.content.service.BargainActivityService;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ms.content.dao.BargainingRecordDao;
import com.ms.content.entity.BargainingRecordEntity;
import com.ms.content.service.BargainingRecordService;


@Service("bargainingRecordService")
public class BargainingRecordServiceImpl extends ServiceImpl<BargainingRecordDao, BargainingRecordEntity> implements BargainingRecordService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BargainActivityDao bargainActivityDao;

    @Autowired
    private BargainingItemDao bargainingItemDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BargainingRecordEntity> page = this.page(
                new Query<BargainingRecordEntity>().getPage(params),
                new QueryWrapper<BargainingRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R userKanj(String uuid,Long uid) {
        String s = stringRedisTemplate.opsForValue().get(uuid);
        System.out.println("取出uuid存的东西"+s);
        if (!StringUtils.isEmpty(s)) {
            //获取存入redis中的帮砍价信息
            BargainingItemEntity bargainingItemEntity = JSONObject.parseObject(s, new TypeReference<BargainingItemEntity>() {
            });
            System.out.println(bargainingItemEntity);

            //取出活动 信息
            Long bkhdId = bargainingItemEntity.getBkhdId();
            QueryWrapper<BargainActivityEntity> wrapper = new QueryWrapper<BargainActivityEntity>().eq("id", bkhdId);
            BargainActivityEntity bargainActivityEntity1 = bargainActivityDao.selectOne(wrapper);
            //判断是否为砍价规则
            if (bargainActivityEntity1.getShopBargainingRules().equals(2)){
                //执行砍到最低价

                //查询最近一次该用户帮砍修改的记录
                BargainingItemEntity bargainingItemEntity1 =  bargainingItemDao.selectOneZjTime(bargainingItemEntity.getUid());
                //判断此时当前价格是否为最低价
                if (bargainingItemEntity1.getGoodsPrice().equals(bargainActivityEntity1.getKafinPrice())){
                    //相等为最低价 则返回
                    return R.error("您所帮助的用户已砍至最低价");
                }else{
                    //不相等则1.砍
                    // 并2.添加记录
                    // 以及3.修改砍价记录表

                    //1.
                    //生成砍价单
                    String s1 = stringRedisTemplate.opsForValue().get(bargainingItemEntity.getGoodsId() + "," + bargainingItemEntity.getUid());
                    List<GoodsEntity> goodsEntities = JSONObject.parseObject(s1, new TypeReference<List<GoodsEntity>>() {
                    });
                    System.out.println("商品砍价集合:"+goodsEntities);
                    //获取最近一次更新商品信息
                    GoodsEntity goodsEntity1 = goodsEntities.get(goodsEntities.size() - 1);
                    System.out.println("最近一次更新商品信息："+goodsEntity1);
                    Random random = new Random();
                    //按每次砍后价格的10%进行砍
                    int i1 = random.nextInt((int) (Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice()))*0.1));

                    GoodsEntity goodsEntity = new GoodsEntity();
                    BeanUtils.copyProperties(goodsEntity1,goodsEntity);
                    //减去砍价的余额进行赋值
                    goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())) - i1));
                    //将最新商品信息赋值到结合中并同步到redis
                    goodsEntities.add(goodsEntity);
                    System.out.println("最新商品砍价集合:"+goodsEntities);
                    String jsonString = JSONObject.toJSONString(goodsEntities);
                    System.out.println("使用JSON转换为String后的字符串: "+jsonString);
                    //砍价信息存入redis
                    stringRedisTemplate.opsForValue().set(goodsEntity1.getId() + "," + bargainingItemEntity.getUid(), JSONObject.toJSONString(goodsEntities));
                    //2.
                    //添加砍价记录表
                    BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
                    bargainingRecordEntity.setBaId(Long.valueOf(bargainingItemEntity.getBkhdId()));
                    bargainingRecordEntity.setUid(Long.valueOf(uid));
                    bargainingRecordEntity.setGoodsId(Math.toIntExact(bargainingItemEntity.getGoodsId()));
                    bargainingRecordEntity.setKnifeName(s);

                    //计算砍了多少钱
                    bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i1));
                    bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(goodsEntity.getGoodsPrice()))-i1);
                    System.out.println(bargainingRecordEntity);
                    int insert = baseMapper.insert(bargainingRecordEntity);
                    System.out.println(insert);

                    //修改砍价订单状态
                    // 判断这次后是否达成砍价
                    // 达成则修改订单状态为 “已砍完” 状态
                    // 不达成则只修改价格 并进行数据库更新
                    if(bargainingRecordEntity.getSyMoney().equals(bargainActivityEntity1.getKafinPrice())){
                        //修改订单状态信息
                        QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid",bargainingItemEntity.getUid()).eq("goods_user_static", 0);
                        BargainingItemEntity bargainingItem = bargainingItemDao.selectOne(eq);
                        bargainingItem.setGoodsPrice(goodsEntity.getGoodsPrice());
                        bargainingItem.setGoodsUserStatic(1);
                        bargainingItem.setXgTime(new Date());
                        rabbitTemplate.convertAndSend("kj.o.update",JSONObject.toJSONString(bargainingItem));
                    }else{
                        //修改订单状态信息
                        QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid",bargainingItemEntity.getUid()).eq("goods_user_static", 0);
                        BargainingItemEntity bargainingItem = bargainingItemDao.selectOne(eq);
                        bargainingItem.setGoodsPrice(goodsEntity.getGoodsPrice());
                        bargainingItem.setXgTime(new Date());
                        rabbitTemplate.convertAndSend("kj.o.update",JSONObject.toJSONString(bargainingItem));
                    }
                    return R.ok();
                }
            }else{
                //执行砍的次数
                String count = stringRedisTemplate.opsForValue().get(bargainingItemEntity.getUid() + "count"+bargainingItemEntity.getGoodsId());
                    //查询最近一次该用户帮砍修改的记录
                    BargainingItemEntity bargainingItemEntity1 =  bargainingItemDao.selectOneZjTime(bargainingItemEntity.getUid());
                    //根据砍价记录获取  砍价活动id求出砍价次数 判断是否达到该次数
                    QueryWrapper<BargainActivityEntity> id = new QueryWrapper<BargainActivityEntity>().eq("id", bargainingItemEntity1.getBkhdId());
                    System.out.println(bargainingItemEntity1);
                    BargainActivityEntity bargainActivityEntity = bargainActivityDao.selectOne(id);

                    //判断是否砍到最大次数
                        if (Integer.parseInt(count) == bargainActivityEntity.getKafinSunCount()) {
                            //满足最大的砍刀条件 直接不砍
                            return R.error("您所帮助的用户已砍完");
                        } else {
                            //生成砍价单
                            String s1 = stringRedisTemplate.opsForValue().get(bargainingItemEntity.getGoodsId() + "," + bargainingItemEntity.getUid());
                            List<GoodsEntity> goodsEntities = JSONObject.parseObject(s1, new TypeReference<List<GoodsEntity>>() {
                            });
                            System.out.println("商品砍价集合:"+goodsEntities);
                            //获取最近一次更新商品信息
                            GoodsEntity goodsEntity1 = goodsEntities.get(goodsEntities.size() - 1);
                            System.out.println("最近一次更新商品信息："+goodsEntity1);
                            Random random = new Random();
                            //按每次砍后价格的10%进行砍Integer.parseInt(String.valueOf())
                            int i1 = random.nextInt((int) (Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice()))*0.1));

                            GoodsEntity goodsEntity = new GoodsEntity();
                            BeanUtils.copyProperties(goodsEntity1,goodsEntity);
                            //减去砍价的余额进行赋值
                            goodsEntity.setGoodsPrice(BigDecimal.valueOf(Integer.parseInt(String.valueOf(goodsEntity1.getGoodsPrice())) - i1));
                            //将最新商品信息赋值到结合中并同步到redis
                            goodsEntities.add(goodsEntity);
                            System.out.println("最新商品砍价集合:"+goodsEntities);
                            String jsonString = JSONObject.toJSONString(goodsEntities);
                            System.out.println("使用JSON转换为String后的字符串: "+jsonString);
                            //砍价信息存入redis
                            stringRedisTemplate.opsForValue().set(goodsEntity1.getId() + "," + bargainingItemEntity.getUid(), JSONObject.toJSONString(goodsEntities));
                            //通过此id砍价次数+1
                            stringRedisTemplate.opsForValue().set(bargainingItemEntity.getUid() + "count"+bargainingItemEntity.getGoodsId(), String.valueOf(Integer.parseInt(count) + 1));

                            //添加砍价记录表
                            BargainingRecordEntity bargainingRecordEntity = new BargainingRecordEntity();
                            bargainingRecordEntity.setBaId(Long.valueOf(bargainingItemEntity.getBkhdId()));
                            bargainingRecordEntity.setUid(Long.valueOf(uid));
                            bargainingRecordEntity.setGoodsId(Math.toIntExact(bargainingItemEntity.getGoodsId()));
                            bargainingRecordEntity.setKnifeName(s);

                            //计算砍了多少钱
                            bargainingRecordEntity.setKnifePrice(BigDecimal.valueOf(i1));
                            bargainingRecordEntity.setSyMoney(Integer.parseInt(String.valueOf(goodsEntity.getGoodsPrice())));
                            System.out.println(bargainingRecordEntity);
                            int insert = baseMapper.insert(bargainingRecordEntity);
                            System.out.println(insert);

                            //修改砍价订单状态
                            // 判断这次后是否达成最大砍价次数
                            // 达成则修改订单状态为 “已砍完” 状态
                            // 不达成则只修改价格 并进行数据库更新
                            if(Integer.parseInt(count) == bargainActivityEntity.getKafinSunCount()-1){
                                //修改订单状态信息
                                QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid",bargainingItemEntity.getUid()).eq("goods_user_static", 0);
                                BargainingItemEntity bargainingItem = bargainingItemDao.selectOne(eq);
                                bargainingItem.setGoodsPrice(goodsEntity.getGoodsPrice());
                                bargainingItem.setGoodsUserStatic(1);
                                bargainingItem.setXgTime(new Date());
                                rabbitTemplate.convertAndSend("kj.o.update",JSONObject.toJSONString(bargainingItem));
                            }else{
                                //修改订单状态信息
                                QueryWrapper<BargainingItemEntity> eq = new QueryWrapper<BargainingItemEntity>().eq("uid",bargainingItemEntity.getUid()).eq("goods_user_static", 0);
                                BargainingItemEntity bargainingItem = bargainingItemDao.selectOne(eq);
                                bargainingItem.setGoodsPrice(goodsEntity.getGoodsPrice());
                                bargainingItem.setXgTime(new Date());
                                rabbitTemplate.convertAndSend("kj.o.update",JSONObject.toJSONString(bargainingItem));
                            }
                            return R.ok();
                        }
            }

        }else{
            return R.error("砍价信息错误，请重试");
        }

    }


}